<?php
/**
* get_tweets.php
* Collect tweets from the Twitter streaming API
* This must be run as a continuous background process
* Latest copy of this code: http://140dev.com/free-twitter-api-source-code-library/
* @author Adam Green <140dev@gmail.com>
* @license GNU Public License
* @version BETA 0.10
*/
require_once('140dev_config.php');

// Extend the Phirehose class to capture tweets in the json_cache MySQL table
require_once('Phirehose.php');
require_once('OauthPhirehose.php');

class Consumer extends OauthPhirehose
{	
  // A database connection is established at launch and kept open permanently
  public $oDB;
  public $screen_names;
  
  public function db_connect() {
    require_once('db_lib.php');
    $this->oDB = new db;
  }
	
  // This function is called automatically by the Phirehose class
  // when a new tweet is received with the JSON data in $status
  public function enqueueStatus($status) {
    $tweet_object = json_decode($status);
    $tweet_id = $tweet_object->id_str;

    // If there's a ", ', :, or ; in object elements, serialize() gets corrupted 
    // You should also use base64_encode() before saving this
    $raw_tweet = base64_encode(serialize($tweet_object));
	
	if(strlen($tweet_id)==0)
	{
		$query = "SELECT MAX(ID_TWEET) FROM MAST_TWITTER_TWITTER";
		$result = $this->oDB->select($query);
		while($row = mysqli_fetch_assoc($result)) {		
			$tweet_id = $row[0] + 1;    	
		}
	}
		
    $field_values = 'ds_raw_tweet = "' . $raw_tweet . '", ' .
      'id_tweet = ' . $tweet_id;
    $this->oDB->insert('TMP_TWITTER_JSON_CACHE',$field_values);
  }
  
  public function get_screen_names(){
  	
  	$screen_names = array( );
  	$query = "SELECT DS_SCREEN_NAME FROM MAST_RESTAURANTS INNER JOIN MAST_TWITTER_ACCOUNTS ON DS_REST_TWITTER = DS_SCREEN_NAME WHERE DS_REST_TWITTER IS NOT NULL AND BL_PARSE = 1 AND ID_LOCALITY = '079'";
  	
  	$result = $this->oDB->select($query);
  
  	if($result === FALSE) {
  		
    	die(mysql_error()); // TODO: better error handling
	}
  	while($row = mysqli_fetch_assoc($result)) {
		
    	$screen_name = $row['DS_SCREEN_NAME'];
    	array_push($screen_names,$screen_name);
  	}
  
  	return $screen_names;
  }
}

// Open a persistent connection to the Twitter streaming API
// Basic authentication (screen_name, password) is still used by this API
$stream = new Consumer(OAUTH_TOKEN, OAUTH_SECRET, Phirehose::METHOD_FILTER);

// Establish a MySQL database connection
$stream->db_connect();

// The keywords for tweet collection are entered here as an array
// More keywords can be added as array elements
// For example: array('recipe','food','cook','restaurant','great meal')
$screen_names = $stream->get_screen_names();

$stream->setTrack($screen_names);

// Start collecting tweets
// Automatically call enqueueStatus($status) with each tweet's JSON data
$stream->consume();

?>